package com.bluemson.service.Impl;

import com.bluemson.dao.ManagerDao;
import com.bluemson.dao.UserDao;
import com.bluemson.entity.*;
import com.bluemson.service.AddService;
import com.bluemson.util.MyBatisUtil;
import com.bluemson.util.PictureUtil;
import com.bluemson.util.TimeUtil;
import org.apache.ibatis.session.SqlSession;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class AddServiceImpl implements AddService {
    private final SqlSession session = MyBatisUtil.getSqlSession();
    UserDao userDao = session.getMapper(UserDao.class);
    @Override
    public void addComment(Comment comment){
        comment.setTime(TimeUtil.newDateTime());
        userDao.addComment(comment);
        session.commit();
        userDao.comment(comment.getArticleId());
        session.commit();
    }
    @Override
    public void addReply(Comment comment){
        comment.setTime(TimeUtil.newDateTime());
        userDao.addReply(comment);
        session.commit();
        userDao.comment(comment.getArticleId());
        session.commit();
    }
    @Override
    public boolean concernPlate(Concern concern){
        if(userDao.checkConcern(concern)==null){
            userDao.concernPlate(concern);
            session.commit();
            userDao.concernUser(concern);
            session.commit();
            return true;
        }else {
            return false;
        }
    }
    @Override
    public boolean addUser(User user) {
        boolean flag = false;
        if(userDao.checkUser(user)==null){
            userDao.addUser(user);
            session.commit();
            flag = true;
        }
        return flag;
    }
    @Override
    public String addHead(MultipartFile picture, HttpServletRequest request,int id) throws IOException {
        User user = new User();
        user.setHead(PictureUtil.getUri(picture,request));
        user.setId(id);
        userDao.addHead(user);
        session.commit();
        return user.getHead();
    }

    @Override
    public String addFile(MultipartFile picture, HttpServletRequest request, int id) throws IOException {
        Article article = new Article();
        article.setFile(PictureUtil.getUri(picture,request));
        article.setId(id);
        userDao.addFile(article);
        session.commit();
        return article.getFile();
    }

    @Override
    public void addArticle(Article article){
        article.setTime(TimeUtil.newDateTime());
        userDao.addArticle(article);
        session.commit();
        userDao.articleCount(article.getPlate());
        session.commit();
    }

    @Override
    public boolean addPlate(Plate plate){
        boolean flag=false;
        ManagerDao managerDao = session.getMapper(ManagerDao.class);
        if(plate.getHost()==null||"".equals(plate.getHost())){
            if(managerDao.checkPlate(plate).isEmpty()){
                plate.setTime(TimeUtil.newDateTime());
                managerDao.addPlateSelf(plate);
                session.commit();
                flag=true;
            }
        }else {
            if(managerDao.checkPlateHost(plate).isEmpty()){
                plate.setTime(TimeUtil.newDateTime());
                managerDao.addPlateHost(plate);
                session.commit();
                flag = true;
            }
        }
        return flag;
    }
    @Override
    public String addCover(MultipartFile picture, HttpServletRequest request,String name) throws IOException {
        Plate plate = new Plate();
        plate.setCover(PictureUtil.getUri(picture,request));
        plate.setName(name);
        ManagerDao managerDao = session.getMapper(ManagerDao.class);
        managerDao.updateCover(plate);
        session.commit();
        return plate.getCover();
    }

    @Override
    public ImgResultDto upLoadImg(List<MultipartFile> list, int articleId,
                                  HttpServletRequest request) {
        //获取当前登录的管理员
        //CmsAdmin admin = (CmsAdmin) SessionUtils.getSession("currenLogintAdmin");
        ImgResultDto imgResultDto = new ImgResultDto();
        //这里定
        String[] urlData = new String[5];
        int index = 0;
        try {
            for(MultipartFile img : list) {
            //获取原始文件名，比如你上传的是　图片．jpg,则fileName＝图片．jpg
                String fileName = img.getOriginalFilename();
                if("".equals(fileName)) {
                    continue;
                }
//            String fileName = myFileName.getOriginalFilename();
                String fileNameExtension = fileName.substring(fileName.lastIndexOf("."));
                String realName = UUID.randomUUID() + fileNameExtension;
                String realPath = request.getSession().getServletContext().getRealPath("/upload");
                File fileDisk = new File(realPath);
                if (!fileDisk.exists()){
                    fileDisk.mkdir();
                }
//			realPath = "E:\\work\\Java\\DMS\\WebContent\\upload";
                File uploadFile = new File(realPath, realName);
                img.transferTo(uploadFile);

//                String finalPath = imgUploadAbsolutePath + imgUploadRelativePath;  //绝对路径　＋　相对路径
//                //为了保证文件名不一致，因此文件名称使用当前的时间戳和4位的随机数，还有原始文件名组成
//                //觉得实际的企业开发不应当使用原始文件名，否则上传者使用一些不好的名字，对于下载者就不好了．
//                //这里为了调试方便，可以加上．
//                String finalFileName =  (System.currentTimeMillis()) + Math.round(Math.random() * 1000)  //文件名动态部分
//                        + fileName; //文件名　原始文件名
//                File newfile = new File( finalPath + finalFileName);
                //保存文件到本地
                //持久化到数据库
                ArticleImg articleImg = new ArticleImg(fileName, realPath,
                      TimeUtil.newDateTime(),articleId);
                userDao.addArticleImg(articleImg);
                session.commit();
                //这里的路径是项目路径＋文件路径＋文件名称
                //这么写不是规范的做法，项目路径应是放在前端处理，只需要发送相对路径和文件名称即可，项目路径由前端加上．
                urlData[index++] = "http://123.56.124.177:8088/BBS-1.0-SNAPSHOT/" +realPath + realName;
                //设置异常代号
                imgResultDto.setErrno(0);
            }
            imgResultDto.setData(urlData);
            //返回Ｄto
            return imgResultDto;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return imgResultDto;
        }

    }

}
